﻿using RestSharp;
using sx_windows.resource;
using sx_windows.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace sx_windows.data.repository.source
{
    public static class Request
    {
        public static void Post(string url, Dictionary<string, string> param, FetchCallback callback)
        {
            HttpThread http = new HttpThread(url, param, callback);
            Thread t = new Thread(new ThreadStart(http._post));
            t.Start();
        }
        public class HttpThread//线程类
        {
            string url;
            Dictionary<string, string> param;
            FetchCallback callback;
            string code = null;
            public HttpThread(string url, Dictionary<string, string> param, FetchCallback callback)
            {
                this.url = url;
                this.param = param;
                this.callback = callback;
            }
            public void _post()
            {
                long timestamp = Tool.GetTimestamp();
                if (param == null)
                {
                    param = new Dictionary<string, string>();
                }
                param.Add("timestamp", timestamp + "");
                string data = getParams(param);
                var client = new RestClient(Const.API_URL + url);
                var request = new RestRequest(Method.POST);
                request.AddHeader("appname", "deskApp");
                code = Tool.MD5.Encode2string(data);
                request.AddHeader("code", code);
                request.AddParameter("application/x-www-form-urlencoded", data, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    callback.onSuccess(FetchResult.Instance(response.Content, timestamp));
                }
                else
                {
                    callback.onError();
                }
            }
            private string getParams(Dictionary<string, string> param)
            {
                var p = from objDic in param orderby objDic.Key select objDic;
                StringBuilder builder = new StringBuilder();
                foreach (var item in p)
                {
                    builder.Append(item.Key).Append("=").Append(item.Value).Append("&");
                }
                builder.Remove(builder.Length - 1, 1);
                return builder.ToString();
            }
        }
    }
}
